package com.unisyou.handler;

import com.unisyou.bean.WXUsersBean;
import com.unisyou.builder.TextBuilder;
import com.unisyou.config.PropertiesConfig;
import com.unisyou.utils.HttpClient;
import com.unisyou.utils.JSONUtils;
import com.unisyou.utils.SignDecode;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 关注处理器
 */
@Component
public class SubscribeHandler extends AbstractHandler {

    @Autowired
    private HttpClient httpClient;
    @Autowired
    private PropertiesConfig propertiesConfig;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) throws WxErrorException {
        try {
            WxMpUser userWxInfo = weixinService.getUserService()
                    .userInfo(wxMessage.getFromUser(), null);
            if (userWxInfo != null) {
                String url = propertiesConfig.getUrl()+propertiesConfig.getSaveWxUserInfoPath();
                WXUsersBean wxUsersBean = WXUsersBean.transfer(userWxInfo);
                String beanToJSONString = JSONUtils.beanToJson(wxUsersBean);
                Map<String,Object> paramsMap = SignDecode.getInstance().encode(beanToJSONString);
                paramsMap.put("token","");
                Map<String,Object> resultMap = httpClient.clientForPostBody(url,paramsMap);
                if(!"0".equals(resultMap.get("resultCode").toString())){
                    this.logger.info("关注保存用户信息失败:{}",resultMap.get("resultMsg").toString());
                }
            }
        } catch (WxErrorException e) {
            if (e.getError().getErrorCode() == 48001) {
                this.logger.info("该公众号没有获取用户信息权限！");
            }
        }

        WxMpXmlOutMessage responseResult = null;
        try {
            responseResult = this.handleSpecial(wxMessage);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        if (responseResult != null) {
            return responseResult;
        }

        try {
            return new TextBuilder().build("感谢关注", wxMessage, weixinService);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        return null;
    }

    /**
     * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
     */
    private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage)
        throws Exception {
        //TODO
        return null;
    }

}
